<template>
  <view class="footer">
    <view v-for="item in navItems" :key="item.path" class="footer-item" :class="{ active: activeRoute === item.path }" @click="handleNavigate(item)">
      <u-icon :name="item.icon" size="48" :color="activeRoute === item.path ? activeColor : inactiveColor"></u-icon>
      <text class="footer-text">{{ item.label }}</text>
    </view>
  </view>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'

defineOptions({
  name: 'Footer'
})

const props = defineProps({
  activePath: {
    type: String,
    default: ''
  }
})

const activeColor = '#e54d42'
const inactiveColor = '#999'

const navItems = [
  { label: '首页', icon: 'home', path: '/pages/index/index' },
  { label: '产品', icon: 'grid', path: '/pages/product/index' },
  { label: '社区', icon: 'chat', path: '/pages/community/index' },
  { label: '我的', icon: 'account', path: '/pages/mine/index' }
]

const currentPath = ref('')

const resolveCurrentPath = () => {
  const pages = getCurrentPages()
  const current = pages[pages.length - 1]?.route
  currentPath.value = current ? `/${current}` : ''
}

onMounted(() => {
  resolveCurrentPath()
})

onShow(() => {
  resolveCurrentPath()
})

const activeRoute = computed(() => props.activePath || currentPath.value)

const handleNavigate = (item) => {
  if (activeRoute.value === item.path) {
    return
  }

  const targetUrl = item.path

  // #ifdef APP-PLUS
  uni.navigateTo({
    url: targetUrl,
    animationType: 'none',
    animationDuration: 0,
    fail: () => {
      uni.reLaunch({
        url: targetUrl
      })
    }
  })
  // #endif

  // #ifndef APP-PLUS
  uni.reLaunch({
    url: targetUrl
  })
  // #endif
}
</script>

<style lang="scss">
@import './index.scss';
</style>
